package darknet.core.impl.net;

import darknet.core.spec.net.Message;
import darknet.core.spec.net.ProtocolSender;
import darknet.core.spec.net.Response;
import darknet.core.spec.net.StreamableMessage;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * Implementation of a protocol sender for base application.
 *
 * @author Yoyo
 */
class BaseProtocolSender implements ProtocolSender {

     /** Base protocol */
    private BaseProtocol protocol = BaseProtocol.getCurrent();

    /** Base application */
    private BaseApplicationImpl application;

    /**
     * Initialise a new base protocol sender.
     *
     * @param application
     */
    public BaseProtocolSender(BaseApplicationImpl application) {

         if (application == null) {
            throw new IllegalArgumentException("application is null");
        }
        this.application = application;
    }

    @Override
    public boolean canSend(Message toSend) {

        if (toSend == null) {
            throw new IllegalArgumentException("toSend is null");
        }

        return protocol.equals(toSend.getHeader().getProtocol());
    }

    @Override
    public Response send(StreamableMessage toSend) throws IOException {

        if (toSend == null) {
            throw new IllegalArgumentException("toSend is null");
        }

        // Send the message.
        return sendMessage(toSend);
    }

    private Response sendMessage(StreamableMessage toSend) throws IOException {

        Response response = null;

        if (toSend.getWrapped() instanceof PingMessage) {

            response = sendPingMessage(toSend);

        }

        return response;

    }

    private Response sendPingMessage(StreamableMessage toSend) throws IOException {

          // Try to send the ListChannel message.
        ObjectOutputStream out = new ObjectOutputStream(toSend.getOutput());
        out.writeObject(toSend.getWrapped());
        out.flush();

        return new OKResponse();
    }


}
